package com.tools.web.interceptor.auth;

import com.tools.common.object.json.JsonKit;
import com.tools.common.object.Note;
import com.tools.common.thread.Timeunit;
import com.tools.middle.redis.client.JedisClusterPlus;
import com.tools.web.interceptor.access.AccessManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 使用 JedisClusterPlus 操作 Redis 集群
 * 完成用户认证功能的管理器
 * */
@Note("使用 JedisClusterPlus 操作 Redis 集群" +
        "完成用户认证功能的管理器")
public final class SingleJedisClusterPlusAuthenticationManager extends GenericAuthenticationManager {

    @Note("使用 JedisPlus 操作 Redis 单机客户端完成用户认证等操作")
    private final JedisClusterPlus jedisClusterPlus;

    @Note("日志对象")
    private static final Logger LOGGER = LoggerFactory.getLogger(SingleJedisClusterPlusAuthenticationManager.class);

    /* **************************************************************************************
     *
     *          构造方法
     *
     * **************************************************************************************
     * */

    public SingleJedisClusterPlusAuthenticationManager(JedisClusterPlus jedisClusterPlus, AuthSource source,
                                                       AuthUserService authUserService) {
        this(jedisClusterPlus, source, authUserService, null);
    }

    public SingleJedisClusterPlusAuthenticationManager(JedisClusterPlus jedisClusterPlus, AuthSource source,
                                                       AuthUserService authUserService, AccessManager accessManager) {
        super(source, authUserService, accessManager);
        this.jedisClusterPlus = Objects.requireNonNull(jedisClusterPlus);
    }

    /* **************************************************************************************
     *
     *          功能方法
     *
     * **************************************************************************************
     * */

    @Override
    protected Logger protected_getLogger() {
        return LOGGER;
    }

    @Override
    protected Timeunit protected_getTimeunitToBeUsed() {
        return Timeunit.SECOND;
    }

    @Override
    protected void protected_loginOut(String key, String deviceTypeId, String uuid,
                                      AuthUser authUser, String separator) {
        this.removeAuthUser(key);
    }

    @Override
    protected Res getAuthUser(String key, AuthToken token) {
        SingleAuthUser authUser = (SingleAuthUser) this.jedisClusterPlus.get(key);
        if(authUser == null) return super.protected_getResIfExpired(token);
        if(Objects.equals(authUser.getUuid(),  token.getUuid()) &&
                Objects.equals(authUser.getDeviceTypeId(), token.getDeviceTypeId())) {
            return new Res(true, authUser);
        }
        return new Res(false, null);
    }

    @Override
    protected void setAuthUser(String key, AuthUser srcAuthUser, AuthToken token) {
        SingleAuthUser authUser = (SingleAuthUser) srcAuthUser;
        authUser.setUuid(token.getUuid());
        authUser.setDeviceTypeId(token.getDeviceTypeId());
        authUser.setUserType(token.getUserType());
        String json = JsonKit.toJSON(authUser);
        this.jedisClusterPlus.setex(key, token.getExpiration(), json);
    }

    @Override
    protected void removeAuthUser(String key) {
        this.jedisClusterPlus.del(key);
    }

    @Override
    protected void updateAuthUser(String key, AuthUser authUser, String separator) {
        String script = "local key = ARGV[1];" +
                        "local newValue = ARGV[2];" +
                        "if redis.call('exists', key) == 1 then" +
                        "    local ttl = redis.call('ttl', key);" +
                        "    redis.call('set', key, newValue);" +
                        "    if ttl > 0 then" +
                        "        redis.call('expire', key, ttl);" +
                        "    end" +
                        "    return 1;" +
                        "else" +
                        "    return 0;" +
                        "end";
        String json = JsonKit.toJSON(authUser);
        this.jedisClusterPlus.eval(script, 0, key, json);
    }
}
